package com.yxuan.springboot.service.impl;

import com.yxuan.springboot.mapper.*;
import com.yxuan.springboot.model.*;
import com.yxuan.springboot.mapper.*;
import com.yxuan.springboot.model.*;
import com.yxuan.springboot.service.TestTypeDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.*;

/**
 * @author zchao
 * TestTypeDetails业务层实现类
 * @date 2023-05-16 14:22:56
 */
@Service
@Transactional
public class TestTypeDetailsServiceImpl extends BaseServiceImpl<TestTypeDetails> implements TestTypeDetailsService {
    @Autowired
    private TestTypeDetailsMapper testTypeDetailsMapper;

    @Autowired
    private TestVersionTopicMapper testVersionTopicMapper;

    @Autowired
    private TestQuestionsMapper testQuestionsMapper;

    @Autowired
    private TestOptionsMapper testOptionsMapper;

    @Autowired
    private TestRecordsMapper testRecordsMapper;

    @Autowired
    private TestScorneirongMapper testScorneirongMapper;

    //    测试首页数据
    @Override
    public HashMap<String, Object> testHome(Map map) throws Exception {
        HashMap<String, Object> result1 = new HashMap<>();
        HashMap<String, Object> result2 = new HashMap<>();
        TestTypeDetails testTypeDetail = new TestTypeDetails();
        testTypeDetail.setHot("1");
        testTypeDetail.setIfusing("1");
//         获取头部的热点测试
        TestTypeDetails testTypeDetail2 = testTypeDetailsMapper.queryObjectByPramas(testTypeDetail);
        result1.put("id", testTypeDetail2.getId());
        result1.put("testname", testTypeDetail2.getTypeName());
        result1.put("pic", testTypeDetail2.getPic());
        result1.put("slogan", testTypeDetail2.getSlogan());
        result1.put("join_num", testTypeDetail2.getJoinNum());
        result2.put("head", result1);
//         TODO 获取所有using测试，不以区块区分
        TestTypeDetails testTypeDetails3 = new TestTypeDetails();
        testTypeDetails3.setIfusing("1");
        testTypeDetails3.setHot("0");
        List<TestTypeDetails> testTypeDetails = testTypeDetailsMapper.queryListByPramas(testTypeDetails3);
        List list2 = new ArrayList();
        for (TestTypeDetails typeDetail : testTypeDetails) {
            HashMap<String, Object> result4 = new HashMap<>();
            result4.put("id", typeDetail.getId());
            result4.put("testname", typeDetail.getTypeName());
            result4.put("pic", typeDetail.getPic());
            result4.put("slogan", typeDetail.getSlogan());
            result4.put("join_num", typeDetail.getJoinNum());
            list2.add(result4);
        }
        result2.put("test_list",list2);
//        TODO 已完成的测试,在测试记录根据 user_id 和 status 查询所有测试记录
        TestRecords testRecords = new TestRecords();
        testRecords.setUserId((String) map.get("user_id"));
        testRecords.setStatus("1");
        List<TestRecords> testRecords1 = testRecordsMapper.queryListByPramas(testRecords);
        List list = new ArrayList<>();
        List list1 = new ArrayList<>();
        if (testRecords1.isEmpty()){
            result2.put("accomplish_text_list","null");
        }else{

            for (TestRecords re : testRecords1){
                HashMap<String,Object> result = new HashMap<>();
                result.put("record_id",re.getId());
                TestTypeDetails testTypeDetails1 = new TestTypeDetails();
                testTypeDetails1.setId(re.getTypeId());
                TestTypeDetails testTypeDetails2 = testTypeDetailsMapper.queryObjectByPramas(testTypeDetails1);
                result.put("join_num",testTypeDetails2.getJoinNum());
                result.put("id",testTypeDetails2.getId());
                result.put("pic",testTypeDetails2.getPic());
                result.put("testname",testTypeDetails2.getTypeName());
                result.put("slogan",testTypeDetails2.getSlogan());
                list.add(result);
            }
            result2.put("accomplish_text_list",list);
        }
//        TODO 未完成的测试
        testRecords.setStatus("0");
        List<TestRecords> testRecords2 = testRecordsMapper.queryListByPramas(testRecords);
        if (testRecords2.isEmpty()){
            result2.put("unfinished_test_list","null");
        }else{
            HashMap<String,Object> result = new HashMap<>();
            for (TestRecords re : testRecords2){
                TestTypeDetails testTypeDetails1 = new TestTypeDetails();
                testTypeDetails1.setId(re.getTypeId());
                TestTypeDetails testTypeDetails2 = testTypeDetailsMapper.queryObjectByPramas(testTypeDetails1);
                result.put("join_num",testTypeDetails2.getJoinNum());
                result.put("id",testTypeDetails2.getId());
                result.put("pic",testTypeDetails2.getPic());
                result.put("testname",testTypeDetails2.getTypeName());
                result.put("slogan",testTypeDetails2.getSlogan());
                result.put("record_id",re.getId());
                list1.add(result);
        }
            result2.put("unfinished_test_list",list1);
        }
        return result2;
    }

    //  TODO  准备测试界面数据
//     点击测试详情，进入准备测试界面：test_type_detils——id、type_name、introduce、pic
//          test_version_type:根据typeid查找version，where using=1
//          test_release:根据 version 和 type_detils_id 查找对应的 topic_num、test_time、illustrate
    @Override
    public HashMap<String, Object> prepareTest(Integer id) throws Exception {
        HashMap<String, Object> result = new HashMap<>();
        TestTypeDetails testTypeDetails = new TestTypeDetails();
        testTypeDetails.setId(id);
        System.out.println(testTypeDetails);
        TestTypeDetails testTypeDetail = testTypeDetailsMapper.queryObjectByPramas(testTypeDetails);
        testTypeDetail.setJoinNum(testTypeDetail.getJoinNum()+1);
        testTypeDetailsMapper.update(testTypeDetail);
        result.put("id", id);
        result.put("testname", testTypeDetail.getTypeName());
        result.put("introduce", testTypeDetail.getIntroduce());
        result.put("pic", testTypeDetail.getPic());
//        test_version_type:根据typeid查找version
        TestTypeDetails testTypeDetails1 = testTypeDetailsMapper.queryObjectById(String.valueOf(id));
        result.put("topic_number", testTypeDetails1.getTopicNum());
        result.put("test_time", testTypeDetails1.getSuggestTime());
        result.put("illustrate", testTypeDetails1.getTypeExplain());
        result.put("version", testTypeDetails1.getVersion());
//        TODO 使用treemap有序存储题目以及答案
//        通过 version 和 typeid 找到topic_id
        TestVersionTopic testVersionTopic = new TestVersionTopic();
        testVersionTopic.setTypeId(id);
        List<TestVersionTopic> testVersionTopicslist = testVersionTopicMapper.queryListByPramas(testVersionTopic);
        System.out.println(testVersionTopicslist+"____________________________________________________________");
//        遍历列表查找题目,
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < testVersionTopicslist.size(); i++) {
            HashMap<Object, Object> result1 = new HashMap<>();
            TestVersionTopic testVersionTopic1 = testVersionTopicslist.get(i);

            TestQuestions testQuestion = new TestQuestions();
            testQuestion.setId(testVersionTopic1.getTopicId());
            TestQuestions testQuestion1 = testQuestionsMapper.queryObjectByPramas(testQuestion);
            result1.put("id", testQuestion1.getId());
            result1.put("content", testQuestion1.getContent());
            result1.put("question_pic", testQuestion1.getQuestionPic());
            result1.put("respondence", "null");
//            通过题目id来查找答案
            TestOptions option = new TestOptions();
            option.setQuestionId(testQuestion1.getId());
            List<TestOptions> testOptionsList = testOptionsMapper.queryListByPramas(option);
//            排序
            for (int m = 0; m < testOptionsList.size() - 1; m++) {
                for (int n = m + 1; n < testOptionsList.size(); n++) {
                    int i1 = (testOptionsList.get(m).getOptionName().charAt(0) - '0');
                    int i2 = (testOptionsList.get(n).getOptionName().charAt(0) - '0');
                    if (i1 > i2) {
                        TestOptions options = testOptionsList.get(m);
                        testOptionsList.set(m, testOptionsList.get(n));
                        testOptionsList.set(n, options);
                    }
                }
            }


            List<Object> list1 = new ArrayList<>();
            for (TestOptions j : testOptionsList) {
                TreeMap<String, Object> result2 = new TreeMap<>();
                result2.put("id", j.getId());
                result2.put("optionName", j.getOptionName());
                result2.put("optionScore", j.getOptionScore());
                result2.put("optionContent", j.getOptionContent());
                list1.add(result2);
            }
            result1.put("options", list1);
            list.add(result1);
        }
        result.put("title", list);
        return result;
    }


//    查看测试结果
    @Override
    public HashMap<String, Object> testScore(Integer recordid) throws Exception {
        HashMap<String, Object> result = new HashMap<>();
        TestRecords testRecords = testRecordsMapper.queryObjectById(String.valueOf(recordid));
        if (testRecords.getStatus().equals("0")){
            result.put("error","该测试记录未完成，没有成绩");
            return result;
        }
        TestScorneirong testScorneirong = new TestScorneirong();
//        根据 类型id 和 version 查找对应的成绩区间s
        testScorneirong.setTypeId(testRecords.getTypeId());
        testScorneirong.setVersion(testRecords.getVersion());
        List<TestScorneirong> testScorneirongs = testScorneirongMapper.queryListByPramas(testScorneirong);
        for (TestScorneirong score:testScorneirongs){
            if (testRecords.getGrade() >= score.getScoreHead() && testRecords.getGrade() <= score.getScoreEnd()){
                result.put("result",score);
                break;
            }else{
                continue;
            }
        }
        return result;
    }

    @Override
    public HashMap<String, Object> useOrNo(Map map) throws Exception {
        HashMap<String, Object> result = new HashMap<>();
        TestTypeDetails testTypeDetails = new TestTypeDetails();
        testTypeDetails.setId((Integer) map.get("id"));
        TestTypeDetails testTypeDetails1 = testTypeDetailsMapper.queryObjectByPramas(testTypeDetails);
        if (testTypeDetails1.getIfusing().equals("0")){
            testTypeDetails1.setIfusing("1");
        }else {
            testTypeDetails1.setIfusing("0");
        }
        testTypeDetailsMapper.update(testTypeDetails1);
        result.put("result",testTypeDetails1.getIfusing());
        return result;
    }

    @Override
    public HashMap<String, Object> updPic(TestTypeDetails entity) throws Exception {
        HashMap<String, Object> result = new HashMap<>();
        testTypeDetailsMapper.update(entity);
        result.put("upd","success");
        return result;
    }

    @Override
    public HashMap<String, Object> headTopic(Map map) throws Exception {
        HashMap<String, Object> result = new HashMap<>();
        String r = String.valueOf(map.get("result"));
        double grade;
        switch (r){
            case("A"):
                grade = 5.00;
                break;
            case("C"):
                grade = 15.00;
                break;
            case("E"):
                grade = 25.00;
                break;
            case("I"):
                grade = 35.00;
                break;
            case("R"):
                grade = 45.00;
                break;
            case("S"):
                grade = 55.00;
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + r);
        }
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        TestRecords testRecords = new TestRecords();
        testRecords.setTypeId(6);
        testRecords.setVersion("1.0");
        testRecords.setSubmitTime(timestamp);
        testRecords.setStatus("1");
        testRecords.setUserId(String.valueOf(map.get("userId")));
        testRecords.setGrade((float) grade);
        testRecordsMapper.insert(testRecords);
//        增加参与测试人数
        TestTypeDetails testTypeDetails = testTypeDetailsMapper.queryObjectById("6");
        testTypeDetails.setJoinNum(testTypeDetails.getJoinNum()+1);
        testTypeDetailsMapper.update(testTypeDetails);
//        返回测试记录id
        TestRecords testRecords1 = testRecordsMapper.queryObjectByPramas(testRecords);
        result.put("recordId",testRecords1.getId());
        return result;
    }
}
